package com.app.core.web.listener;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.app.core.common.AppBizCache;
import com.app.core.common.AppCons;
import com.app.core.util.SysConfig;
import com.app.core.web.filter.SysLogInterceptor;
import com.app.core.web.util.AppContextUtil;

/**
 * 
 * TODO spring 容器初始化后监听器
 * 
 * @since v0.1
 * @author zxf
 * @created 2015年6月2日 下午2:42:27
 * @deprecated
 */
public class ApplicationListener implements ServletContextListener {

	private static final Logger log = LoggerFactory.getLogger(ApplicationListener.class);

	public void contextInitialized(ServletContextEvent contextEvent) {
		// 把base放到上下文中
		ServletContext sc = contextEvent.getServletContext();
		sc.setAttribute("base", sc.getContextPath());
		sc.setAttribute("path", sc.getContextPath());
		sc.setAttribute("appName", "咕哒猎人");
		sc.setAttribute("cpath", sc.getContextPath() + "/" + SysConfig.get("app.cpath"));
		
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		AppContextUtil.setContext(wac);
		// 初始化 配置文件
		initAppConfig(contextEvent);
		// 初始化数据字典
		intDict();

		// 日志路径配置
		initLogModule();

		// 网站基本数据配置
		initBaseDataConfig();

	}

	private void initBaseDataConfig() {
		try {
			URL url = ResourceUtils.getURL("classpath:data/base_data_config.json");
			String data = FileUtils.readFileToString(new File(url.getFile()), "utf-8");
			AppBizCache.baseConfig = JSON.parseObject(data, JSONObject.class);
		} catch (Exception e) {
			log.error("加载classpath:biz_dict.json失败。", e);
		}
	}

	private void intDict() {
		try {
			URL url = ResourceUtils.getURL("classpath:data/biz_dict.json");
			String data = FileUtils.readFileToString(new File(url.getFile()), "utf-8");
			AppBizCache.initDict(data);
		} catch (Exception e) {
			log.error("加载classpath:biz_dict.json失败。", e);
		}
	}

	private void initAppConfig(ServletContextEvent contextEvent) {
		try {
			URL url = ResourceUtils.getURL("classpath:app-config.properties");
			SysConfig.loadProperties(url);
			Set<Object> keySet = SysConfig.CONFIG.keySet();
			for (Object key : keySet) {
				log.warn(key + "=" + SysConfig.get((String) key));
			}
		} catch (FileNotFoundException e) {
			log.error("加载app-config.properties失败。", e);
		}

		initFileUploadPath(contextEvent);
	}

	/**
	 * 初始化需要初始化的路径
	 * 
	 * @since v0.1
	 * @author zxf
	 * @created 2015年6月8日 下午1:12:14
	 */
	private void initFileUploadPath(ServletContextEvent contextEvent) {
		try {
			AppCons.FILEUPLOAD_SERVER = SysConfig.get("fileupload.server");
			String contextpath = contextEvent.getServletContext().getRealPath("/");
			String authPath = SysConfig.get("fileupload.auth.path");
			String realPath = null;
			String webPath = null;
			if (authPath.startsWith("contextpath:")) {
				webPath = authPath.replace("contextpath:", "");
				realPath = contextpath + webPath;
				AppCons.FILEUPLOAD_AUTH_PATH_IS_CONTEXT = true;
			} else {
				webPath = SysConfig.get("fileupload.auth.path.web");
				realPath = authPath;
			}

			if (StringUtils.isNoneBlank(SysConfig.get("fileupload.auth.path.web"))) {
				webPath = SysConfig.get("fileupload.auth.path.web");
			}

			File file = new File(realPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			AppCons.FILEUPLOAD_AUTH_PATH = webPath;
			AppCons.FILEUPLOAD_AUTH_REAL_PATH = realPath;
			log.warn("文件上传路径(鉴权): {}", realPath);

			String openPath = SysConfig.get("fileupload.open.path");
			realPath = null;
			webPath = null;
			if (openPath.startsWith("contextpath:")) {
				webPath = openPath.replace("contextpath:", "");
				realPath = contextpath + webPath;
				AppCons.FILEUPLOAD_OPEN_PATH_IS_CONTEXT = true;
			} else {
				webPath = SysConfig.get("fileupload.open.path.web");
				realPath = openPath;
			}

			if (StringUtils.isNoneBlank(SysConfig.get("fileupload.open.path.web"))) {
				webPath = SysConfig.get("fileupload.open.path.web");
			}

			File file2 = new File(realPath);
			if (!file2.exists()) {
				file2.mkdirs();
			}
			AppCons.FILEUPLOAD_OPEN_PATH = webPath;
			AppCons.FILEUPLOAD_OPEN_REAL_PATH = realPath;
			log.warn("文件上传路径(开放): {}", realPath);
		} catch (Exception e) {
			log.warn("初始化文件上传路径异常", e);
		}
	}

	private void initLogModule() {
		try {
			URL url = ResourceUtils.getURL("classpath:logModule.json");
			String data = FileUtils.readFileToString(new File(url.getFile()), "utf-8");

			JSONArray jsonArray = JSON.parseArray(data);

			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				SysLogInterceptor.LOG_MAP.put(jsonObject.getString("url"), jsonObject);
			}
		} catch (Exception e) {
			log.error("加载classpath:logModule.json失败。", e);
		}
	}

	public void contextDestroyed(ServletContextEvent contextEvent) {
	}
}
